import React from 'react';
import { Checkbox, Button, Tools, Toast, Modal, Icon, Picker, ActionSheet, InputItem, SwipeAction, List } from 'weaver-mobile';
import { inject, observer } from 'mobx-react';
import { Route, withRouter, Switch, Redirect } from 'react-router-dom';
import { SortableContainer, SortableElement, SortableHandle, arrayMove } from 'react-sortable-hoc';
import { getMultiStrFromBase64, getCurrentLabel } from './../../components/follow/followUtil';
const userLanguage = window.e9_locale.userLanguage;
const alert = Modal.alert;
let thealert=alert();
const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let wrapProps;
if (isIPhone) {
  wrapProps = {
    onTouchStart: e => e.preventDefault(),
  };
}
const getLabel = Tools.getLabel;
const CheckboxItem = Checkbox.CheckboxItem;
const AgreeItem = Checkbox.AgreeItem;

@inject('followStore', 'attentionStore')
@withRouter
@observer
export default class TagManage extends React.Component {
  state = {
    value: '重要',
    sValue: 0,
    Levelvisible: false,
    selected: '',
    clicked: 'none',
    tagList: ['importantLevel2', 'importantLevel1', 'importantLevel0'],
    disabled: false
  };
  componentDidMount() {
    const { followStore } = this.props;
    const { getAttentionTypeSet } = followStore;
    getAttentionTypeSet();
  }
  componentWillUnmount() {
    thealert.close()
    clearTimeout(this.timerID);
  }
  toHistory = (val) => {
    //val ? this.props.history.push(val) : this.props.history.go(-1);
    this.props.history.go(-1);
  }

  handleClick = () => {
  }

  goToEdit = (val) => {
    const { followStore, store } = this.props
    const { followId, setState, followList } = followStore
    if (val != '') {
      let result = followList.find((value, index, arr) => {
        return value.id == val
      })
      setState({ showname: result.showname, followId: val, showcolor: result.colorval }) 
    } else {
      setState({ showname: '', followId: '', showcolor: '' })
    }
    this.getFowardpath()
  }
  getFowardpath = () => {
    if (this.props.type == 'detailpage') {
      this.props.history.push('/req/tagEdit')
    } else if (this.props.type == 'workflowpage') {
      const { cordDatas } = this.props.store;
      let route = "/center/doing";
      if (cordDatas.route) {
        route = cordDatas.route;
      }
      this.props.history.push(route + '/follow/tagManage/tagEdit')
    } else if (this.props.type == 'supervise') {
      const { location } = this.props
      this.props.history.push(location.pathname + '/tagEdit')
    } else if (this.props.type == 'attentionpage') {
      const { attentionStore } = this.props;
      const nowStore = attentionStore.nowListAd.route;
      this.props.history.push(nowStore + '/follow/tagManage/tagEdit')
    } else if (this.props.type == 'tagSetting') {
      const { attentionStore } = this.props;
      const nowStore = attentionStore.nowListAd.route;
      this.props.history.push(nowStore + '/follow/tagManage/tagEdit')
    }
  }
  getBackpath = () => {
    this.props.history.go(-1)
  }
  delete = (value) => {
    const { followStore } = this.props
    const { delfollowids, fokllowId, showname, showcolor, setState, saveAttentionTypeSet } = followStore
    followStore.followList.map((val, index) => {
      if (val.id == value) {
        followStore.followList.splice(index, 1)
        followStore.delfollowids += value + ","
      }
      val.showname.includes("base64_")?val.showname = getMultiStrFromBase64(val.showname):""
    })
    followStore.followList.map((val, index) => {
      val.showname.includes("base64_")?val.showname = getMultiStrFromBase64(val.showname):""
    })
    saveAttentionTypeSet({
      src: 'saveData',
      delIds: value,
      data: JSON.stringify(followStore.followList)
    })
  }

  Dodelete = (value) => {
    thealert=alert('', getLabel('511459', '确认要删除此关注类型吗？'), [
      { text: getLabel('31129', "取消"), onPress: () => {} },
      { text: getLabel('826', "确定"), onPress: () => { this.delete(value) } },
    ])
  }

  caution = () => {
    thealert=alert('', getLabel('511460', '关注类型已被使用，不能删除!'),[{ text: getLabel('826', "确定"), onPress: () => {} }]);
  }

  getFontColor = (value) => {
    let red = parseInt(value.substring(1, 3), 16)
    let green = parseInt(value.substring(3, 5), 16)
    let blue = parseInt(value.substring(5, 7), 16)
    let res = red * 0.299 + green * 0.587 + blue * 0.114
    if (res > 186) {
      return "#000000"
    } else {
      return "#ffffff"
    }
  }

  doSave = () => {
    const { followStore, store,attentionStore } = this.props
    const { delfollowids, followId, showname, showcolor, saveAttentionTypeSet,saveAttention } = followStore
    const { setState, cordDatas } = store
    const { getTree,onSearch } = attentionStore
    let _this = this
    followStore.followList.map(item=>{
      item.showname=getMultiStrFromBase64(item.showname);
    })
    getTree();
    saveAttentionTypeSet({
      src: 'saveData',
      delIds: delfollowids,
      data: JSON.stringify(followStore.followList)
    }, cordDatas.mode)
    getTree();
    onSearch();

    followStore.viewlist.map(t=>{
      followStore.followList.map(v=>{
        if(t.id==v.id){
          t.showname = v.showname;
        }
      })
    })
    _this.getBackpath()
  }

  onSortStart = () => {
    this.disabled = true;
  }

  onSortEnd = ({ oldIndex, newIndex }) => {
    this.timerID = setTimeout(
      () => {
        this.disabled = false;
        this.forceUpdate();
      }, 1);
    const { followStore } = this.props;
    followStore.followList = arrayMove(followStore.followList, oldIndex, newIndex);
  }

  render() {
    const { followStore } = this.props;
    const { followList, disableArray } = followStore;
    const RenderList = SortableContainer(List);
    const RenderListItem = SortableElement(SwipeAction);
    const RenderListProps = { onSortStart: this.onSortStart, onSortEnd: this.onSortEnd, useDragHandle: true, lockAxis: "y" };
    const RenderSortableHandle = SortableHandle(Icon);
    return (
      <div className="follow">
        <div className="manageContent_top" onClick={() => { this.goToEdit('') }} >
          <label><Icon type="plus" style={{ width: "18px", height: "18px",position:"relative",top:"-2px",left:"8px" }} /></label>
          <label style={{ fontSize: "14px" }}>{getLabel('511445','添加关注类型')}</label>
        </div>
        <div className="manageContent_middle"  >
          <RenderList {...RenderListProps}>
            {
              followList.map(((val, i) => {
                let canDelete = false;
                if (disableArray.findIndex((value) => { return value == val.id }) <= -1) {
                  canDelete = true;
                }
                return (<RenderListItem
                  className="sortableHelper"
                  key={`item-${i}`}
                  index={i}
                  disabled={this.disabled}
                  autoClose
                  right={[
                    {
                      text: getLabel('91','删除'),
                      onPress: canDelete ? () => { this.Dodelete(val.id) } : () => { this.caution() },
                      style: { backgroundColor: '#F4333C', color: 'white', width: "100px" },
                    },
                  ]}
                >
                  <div className="manageContent_middle_item" data-dec={val.id} key={val.id} >
                    <label onClick={() => { this.goToEdit(val.id) }} ><Icon type="editor" /></label>
                    <label className="label_for_checkbox" style={{ background: val.colorval, color: this.getFontColor(val.colorval) }}>{ getCurrentLabel(getMultiStrFromBase64(val.showname),userLanguage)}</label>
                    <RenderSortableHandle type="more-3" /> 
                  </div> 
                </RenderListItem>)
              }))
            }
          </RenderList>
        </div>
        <div className="manageContent_bottom">
          <Button type="primary" onClick={() => { this.doSave() }} >{getLabel('86', '保存')}</Button>
        </div>
      </div>
    )
  }
}
